<?php

namespace app\api\service\pay;


use app\api\model\BoxCollect;
use app\api\model\PickUp as PickUpModel;
use app\api\service\coupon\MyCoupon;
use app\api\service\game\Point;
use app\api\service\User;
use app\common\enum\order\OrderStatus;
use app\common\enum\order\PayStatus;
use app\common\library\helper;
use app\common\model\Order;
use app\common\model\OrderAddress;
use think\facade\Db;
use think\facade\Log;

class PostageOrderPay extends PaySuccess
{
    public function onSuccess(array $payment, int $payType)
    {
        Db::startTrans();
        try{
            // 订单更新
            $order = Order::where('order_no', $payment['order_no'])->find();
            $order->pay_status = PayStatus::SUCCESS;
            $order->trans_no = $payment['transaction_id'];
            $order->order_status = OrderStatus::COMPLETED;
            $order->pay_time = time();
            $order->save();
            $address = OrderAddress::where('order_id',$order->order_id)->find();
            $collect_ids = json_decode($order->extra,true);
            //创建提货记录
            $res = PickUpModel::create([
                'user_id'     => $order->user_id,
                'pick_no'     => orderNo(),
                'name'        => $address->name ,
                'phone'       => $address->phone,
                'pcr_address' => $address->pcr_address,
                'detail'      => $address->detail,
            ]);
            if (!$res) {
                throw new \Exception("提货失败");
            }
            // 更新提货商品
            BoxCollect::update([
                'status'     => 1,
                'pick_up_id' => $res->id,
                'postage_order_id' => $order->order_id
            ], [['collect_id', 'IN', $collect_ids]]);

            if($order->coupon_id > 0){
                //核销优惠券
                Log::channel('wxpay')->info('邮费订单核销优惠券：'.$order->coupon_id);
                $res = app(MyCoupon::class)->destruction($order->user_id,$order->coupon_id,$order->order_id,$order->coupon_num);
                if(!$res){
                    return false;
                }
            }

            Db::commit();
            return true;
        }catch (\Exception $e){
            Db::rollBack();
            Log::channel('wxpay')->info('订单号：'.$payment['order_no'].'支付失败');
            Log::channel('wxpay')->info('失败原因：'.$e->getMessage());
            return false;
        }

    }

    public function callSuccess()
    {

    }
}